package com.qf.login;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.bo.LoginLogBO;
import com.qf.dao.LoginLogDao;
import com.qf.enums.ObjectFactory;
import com.qf.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @USER: Administrator
 * @DATE: 2025/8/30 下午11:50
 * @VERSION: 1.0.0
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private LoginLogDao loginLogDao;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 设置响应类型为JSON格式，以便返回JSON格式的响应数据。
        response.setContentType("application/json;charset=UTF-8");

        // 记录登录失败日志
        loginLogDao.insertLoginLog(LoginLogBO.LoginFailure(request.getParameter("username"), request,exception.getMessage())); // 构建响应数据

        // 使用ObjectFactory创建ObjectMapper实例，并返回失败的响应数据
        ObjectMapper objectMapper = ObjectFactory.INSTANCE.createInstance(ObjectMapper.class);
        response.getWriter().write(objectMapper.writeValueAsString(ResultVO.fail("登录失败：" + exception.getMessage())));
    }
}
